package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //用户登录
    public Map login(String username, String password, String code, String uuid) {
        //1.比较redis中的验证码和用户的验证码
        String rediscode = redisTemplate.opsForValue().get("CODE" + uuid);
        //1.1判断验证码
        if(StringUtils.isEmpty(rediscode) || !rediscode.equals(code)){
            //1.2如果验证码错误，抛出异常
            throw new BusinessException("验证码错误");
        }

        //1.3如果验证码正确，删除redis验证码
        redisTemplate.delete("CODE" + uuid);
        //2.比较用户名和密码和数据库的是否一致
        //2.1 根据用户查询用户
        QueryWrapper<Admin> qw  = new QueryWrapper<>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        //2.2 对用户输入的密码进行加密
         password = SecureUtil.md5(password);
        //2.3 比较用户输入的密码和加密后的密码是否一致
        if (admin ==null ||  !admin.getPassword().equals(password)){
            throw  new BusinessException("用户名或密码错误");
        }
        //3.生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",admin.getId());
        String token = JwtUtils.getToken(tokenMap);
        //4.返回
        Map retMap = new HashMap();
        retMap.put("token",token);
        return retMap;


    }

    //获取管理员信息
    public AdminVo profile() {
        //1.从ThreadLocal中获取管理员id
        Long userId = AdminHolder.getUserId();
        //2.根据Id查询管理员对象
        Admin admin = adminMapper.selectById(userId);
        //3.返回
        return AdminVo.init(admin);
    }
}
